/**
 * 模拟 cat /etc/passwd | grep root 的实现
*/

#include <stdio.h>
#include <stdlib.h>

#include <unistd.h>

int main(int argc, char **argv)
{

    int pipe_fds[2];
    if (pipe(pipe_fds) < 0)
    {
        perror("pipe error: ");
        exit(EXIT_FAILURE);
    }

    pid_t pid = fork();
    if (0 > pid)
    {
        perror("fork error: ");
        exit(EXIT_FAILURE);
    }
    else if (0 == pid)
    {
        close(pipe_fds[1]); // 关闭写

        if (dup2(pipe_fds[0], STDIN_FILENO) == -1)
        {
            perror("dup2 error: ");
            exit(EXIT_FAILURE);
        }
        printf("\n");
        
        execl("/bin/grep", "/bin/grep", "root", NULL);
    }
    else
    {
        close(pipe_fds[0]); // 关闭读

        if (dup2(pipe_fds[1], STDOUT_FILENO) == -1)
        {
            perror("dup2 error: ");
            exit(EXIT_FAILURE);
        }

        execl("/bin/cat", "/bin/cat", "/etc/passwd", NULL);
    }

    return 0;
}